package dfa;

import javax.print.DocFlavor;
import java.util.HashMap;
import java.util.List;

public class Atoi09 {
    class DFA {
        HashMap<String, String[]> stateTable = new HashMap<>();
        final String START = "start";
        final String SIGNED = "signed";
        final String ISNUMBER = "in_number";
        final String END = "end";
        String state = START;
        int sign = 1;
        int ans = 0;

        public DFA() {
            stateTable.put(START, new String[]{START, SIGNED, ISNUMBER, END});
            stateTable.put(SIGNED, new String[]{END, END, ISNUMBER, END});
            stateTable.put(ISNUMBER, new String[]{END, END, ISNUMBER, END});
            stateTable.put(END, new String[]{END, END, END, END});
        }

        public int getCol(char c) {
            if (c == ' ')
                return 0;
            if (c == '+' || c == '-')
                return 1;
            if (Character.isDigit(c))
                return 2;
            return 3;
        }

        public void process(char c) {
            int col = getCol(c);
            state = stateTable.get(state)[col];
            if (state.equals(SIGNED))
                sign = c == '+' ? 1 : -1;
            if (state.equals(ISNUMBER)) {
                if (sign == 1) {
                    if (Character.getNumericValue(c) > Integer.MAX_VALUE - ans * 10) {//判断是否越界
                        state = END;
                        ans = Integer.MAX_VALUE;
                    } else
                        ans = ans * 10 + Character.getNumericValue(c);
                } else {//sign == -1
                    if (ans < Integer.MIN_VALUE/10||-Character.getNumericValue(c) < Integer.MIN_VALUE - ans * 10) {//判断是否越界
                        state = END;
                        ans = Integer.MIN_VALUE;
                    } else
                        ans = ans * 10 - Character.getNumericValue(c);
                }
            }
        }
    }

    public int myAtoi(String str) {
        DFA automaton = new DFA();

        for (int i = 0; i < str.length();i++) {
            automaton.process(str.charAt(i));
        }
        return automaton.ans;
    }

    public static void main(String[] args) {
        Atoi09 demo = new Atoi09();
        System.out.println(Integer.MIN_VALUE);
        System.out.println(demo.myAtoi("-2147483649"));
    }
}

